package com.why.whyoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.why.whyoj.common.ErrorCode;
import com.why.whyoj.constant.CommonConstant;
import com.why.whyoj.exception.BusinessException;
import com.why.whyoj.judge.JudgeService;
import com.why.whyoj.mapper.QuestionSubmitMapper;
import com.why.whyoj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.why.whyoj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.why.whyoj.model.entity.Question;
import com.why.whyoj.model.entity.QuestionSubmit;
import com.why.whyoj.model.entity.User;
import com.why.whyoj.model.enums.QuestionSubmitStatusEnum;
import com.why.whyoj.model.vo.QuestionSubmitQueryVO;
import com.why.whyoj.model.vo.QuestionVO;
import com.why.whyoj.service.QuestionService;
import com.why.whyoj.service.QuestionSubmitService;
import com.why.whyoj.service.UserService;
import com.why.whyoj.model.vo.UserVO;
import com.why.whyoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
* @author 22950
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2024-04-08 23:19:45
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;
    @Resource
    private UserService userService;
    @Resource
    @Lazy
    private JudgeService judgeService;

    /**
     *
     * @param records, user
     * @return
     */
    @Override
    public List<QuestionSubmitQueryVO> questionSubmitListToVoList(List<QuestionSubmit> records, User user) {
        int length = records.size();
        long[] userIds = new long[length];
        long[] questionIds = new long[length];
        List<User> userList = new ArrayList<>();
        List<Question> questionList = new ArrayList<>();
        List<QuestionSubmitQueryVO> questionSubmitQueryList = new ArrayList<>();
        for (int i = 0; i < length; i++) {
           userIds[i] = records.get(i).getUserId();
           questionIds[i] = records.get(i).getQuestionId();
        }
        for (long userId : userIds) userList.add(userService.getById(userId));
        for (long questionId : questionIds) questionList.add(questionService.getById(questionId));
        for (int i = 0; i < length; i++) {
            QuestionSubmitQueryVO questionSubmitQueryVO = new QuestionSubmitQueryVO();
            QuestionSubmit questionSubmit = records.get(i);
            BeanUtils.copyProperties(questionSubmit, questionSubmitQueryVO);
            questionSubmitQueryVO.setUserVO(UserVO.objToVo(userList.get(i)));
            questionSubmitQueryVO.setQuestionVO(QuestionVO.objToVo(questionList.get(i)));
            questionSubmitQueryList.add(questionSubmitQueryVO);
            if (!userService.isAdmin(user) && !(user.getId().equals(records.get(i).getUserId()))) {
                questionSubmitQueryVO.setCode(null);
            }


        }
        return questionSubmitQueryList;
    }

    /**
     * 提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        if (questionSubmitAddRequest.getLanguage() == null) throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        Question question = questionService.getById(questionSubmitAddRequest.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(loginUser.getId());
        BeanUtils.copyProperties(questionSubmitAddRequest, questionSubmit);
        questionSubmit.setJudgeInfo("{}");
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WATTING.getValue());
        boolean result = this.save(questionSubmit);
        Long id = questionSubmit.getId();
        CompletableFuture.runAsync(() -> {
            judgeService.doJudge(id);
        });
        if (result) return id;
        else throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }

    @Override
    public QuestionSubmitQueryVO getQuestionSubmitById(long questionSubmitId, User user) {
        Long currentId = user.getId();
        QuestionSubmit questionSubmit = this.getById(questionSubmitId);
        Long questionId = questionSubmit.getQuestionId();
        Long userId = questionSubmit.getUserId();
        QuestionSubmitQueryVO questionSubmitQueryVO = QuestionSubmitQueryVO.objToVo(questionSubmit);
        User aimUser = userService.getById(userId);
        Question aimQuestion = questionService.getById(questionId);
        UserVO userVO = UserVO.objToVo(aimUser);
        QuestionVO questionVO = QuestionVO.objToVo(aimQuestion);
        questionSubmitQueryVO.setUserVO(userVO);
        questionSubmitQueryVO.setQuestionVO(questionVO);
        if (!userService.isAdmin(user) && !(currentId.equals(userId))) {
            questionSubmitQueryVO.setCode(null);
        }
        return questionSubmitQueryVO;
    }

    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        Long questionSubmitId = questionSubmitQueryRequest.getQuestionSubmitId();
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionSubmitId), "id", questionSubmitId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_DESC),
                sortField);
        return queryWrapper;
    }

}




